<?php
namespace app\admin\controller;


use app\admin\model\Activity;
use app\admin\model\Reward;
use app\admin\model\Setting;

use app\lib\exception\ActivityException;
use app\lib\exception\SuccessMessage;
use app\lib\validate\IDMustBePostiveInt;
use think\Config;


class Market extends Base {
    //活动管理
    public function activity()
    {
        $list = Activity::with(['order','user'])->order("id desc")->paginate(8);
        $this->assign('list', $list);
        return view();
    }
    
    //提现
    public function withdraw() {

        return '提现';
    }
    
    //活动设置
    public function activitysetting()
    {
        $list = Setting::all();
        $this->assign('list', $list);
        return view();
    }

    public function activitysetting_act()
    {
        $postdata = request()->post();
        if(in_array('area',$postdata) ||  empty($postdata['area'])){
            $postdata['area'] = 0;
        }
        $settingObj = new Setting();
       foreach($postdata as $k=>$v){
           $settingObj->allowField(true)->save([
               'value' => $v
           ],['key' => $k]);
       }
        throw new SuccessMessage();
    }
    //审核
    public function pass($id)
    {
        (new IDMustBePostiveInt())->goCheck();
        $data = Activity::with(['order'])->where("id","=",$id)->find();
        //已审核情况

        if($data->getData('status') !== 0){
            throw new ActivityException([
                'msg' => '该活动已经审核'
            ]);
        }
        //未支付情况
        if($data['order']->getData('status') == 1){
            throw new ActivityException([
               'msg' => '该订单未支付'
            ]);
        }
        //生成红包,平分or不平分
        $arr = [];
        if($data['is_divide']==0){
            $arr = randBonus($data['all_money_num'],$data['person'],0);
        }else{
            $arr = randBonus($data['all_money_num'],$data['person'],1);
        }
        foreach($arr as $k=>$v){
            $arr[$k]['activity_id'] = $id;
        }
        $rewardObj = new Reward();
        $res = $rewardObj->saveAll($arr);
        Activity::update(['status' => 1],['id' => $id]);
        throw new SuccessMessage();

    }
    public function activityshow($id)
    {
        (new IDMustBePostiveInt())->goCheck();
        $list = Activity::where("id",$id)->with(["order","user"])->find();
        $this->assign('list', $list);
        return view();
    }




    //激活码操作日志
    public function log() {
        $this->assign('list', Log::where('type', 'neq', 2)->order('create_time', 'DESC')->select());
        return view();
    }

    //日志详情
    public function LogDetail() {
        $id = Request::instance()->param('id');
        $list = Log::where('id', 'eq', $id)->find();
        $data = (array)json_decode($list['data']);

        $this->assign('data', $data);
        $this->assign('list', $list);
        return view();
    }

    //存日志
    public function saveLog($msg, $list = array()) {
        $log = array(
            'action' => $msg,
            'operation_id' => session('admin_id'),
            'operation_name' => session('admin_name'),
            'data' => json_encode($list),
        );
       Log::create($log);
    }

    //回收激活码页面
    public function codeCallBack() {
        $agent_id = Request::instance()->param('agent_id');
        $agentContent = Agent::get($agent_id);
        $agentContent['total'] = KeyModel::where('is_active', 'neq', '-1')->where(array('agent_id' => $agent_id))->count();
        $agentContent['enabled'] = KeyModel::where('is_active', 'eq', '1')->where(array('agent_id' => $agent_id))->count();

        $this->assign('list', $agentContent);
        return view();
    }
    
    //回收激活码逻辑实现
    public function codeCallBackLogic() {
        if(Request::instance()->post()) {
            $data = Request::instance()->post();

            if(isset($data['allCode']) && !empty($data['allCode'])) { //执行的是回收所有激活码
                $res = (new keyModel)->codeCallBack($data['agent_id'], '', 'all');
            }else {//回收部分
                (new CodeCallBack)->gocheck();
                if($data['quantity'] > ($data['total'] - $data['enabled'])) {
                    throw new LoginException([
                        'msg' => '没有足够的自由激活码'
                    ]);
                }
                if($data['quantity'] == 0) {
                    throw new LoginException([
                        'msg' => '激活码数量不能为 0'
                    ]);
                }
                $res = (new keyModel)->codeCallBack($data['agent_id'], $data['quantity']);
            }

            if($res) {
                //写入日志
                $log = array(
                    '代理商名字',
                    $data['agent_name'],
                    '代理商ID',
                    $data['agent_id'],
                    '回收激活码个数',
                    $res['num'],
                    '回收激活码的ID',
                    $res['data']
                );
                $this->saveLog('回收 代理商激活码', $log);

                throw new SuccessMessage([
                    'msg' => '成功回收'.$data['agent_name'].'代理商 '.$res['num'].' 个激活码'
                ]);
            }else {
                throw new LoginException([
                    'msg' => $this->error()
                ]);
            }
            
        }
    }
}